package com.course.service;

import com.course.dao.XueshengCourseSelectionDAO;
import com.course.entity.Course;
import com.course.entity.CourseSelection;
import com.course.util.DatabaseUtil;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class CourseSelectionService {
    private static final String SELECTION_FILE = "selections.dat";
    private final CourseService courseService;
    private final XueshengCourseSelectionDAO courseSelectionDAO;

    public CourseSelectionService() {
        this.courseService = new CourseService();
        this.courseSelectionDAO = new XueshengCourseSelectionDAO();
    }

    // 学生选课
    public String selectCourse(int studentId, int courseId) {
        List<CourseSelection> studentSelections = courseSelectionDAO.getCourseSelectionsByStudentId(studentId);

        // Check if student has already selected this course (status '已选') or has a dropped course (status '已退选')
        CourseSelection existingSelection = null;
        for (CourseSelection selection : studentSelections) {
            if (selection.getCourseId() == courseId) {
                if ("已选".equals(selection.getStatus())) {
                    return "ALREADY_SELECTED_BY_ID"; // Student already selected this course by ID
                } else if ("已退选".equals(selection.getStatus())) {
                    existingSelection = selection;
                    break; // Found an existing dropped selection
                }
            }
        }

        Course courseToSelect = courseService.getCourseById(courseId);
        if (courseToSelect == null) {
            return "COURSE_NOT_FOUND"; // Course does not exist
        }

        // Check if student has already selected a course with the same description
        Set<String> selectedCourseDescriptions = studentSelections.stream()
                .filter(s -> "已选".equals(s.getStatus())) // Only consider actively selected courses
                .map(s -> courseService.getCourseById(s.getCourseId()))
                .filter(c -> c != null)
                .map(Course::getCourseDescription)
                .collect(Collectors.toSet());

        System.out.println("Selected Course Descriptions for student " + studentId + ": " + selectedCourseDescriptions);

        if (selectedCourseDescriptions.contains(courseToSelect.getCourseDescription())) {
            return "ALREADY_SELECTED_SAME_DESCRIPTION"; // Student already selected a course with the same description
        }

        // Check if course is full
        long currentStudents = courseSelectionDAO.getCourseSelectionsByCourseId(courseId).size();
        if (currentStudents >= courseToSelect.getMaxCapacity()) {
            return "COURSE_FULL"; // Course is full
        }

        // If an existing dropped selection is found, update its status
        if (existingSelection != null) {
            existingSelection.setStatus("已选");
            if (courseSelectionDAO.updateCourseSelection(existingSelection)) {
                return "SUCCESS";
            } else {
                return "DB_UPDATE_FAILED";
            }
        } else {
            // Otherwise, create a new selection
            CourseSelection selection = new CourseSelection(
                    0, // ID will be generated by database
                    studentId,
                    courseId,
                    0.0,
                    "已选"
            );
            if (courseSelectionDAO.addCourseSelection(selection)) {
                return "SUCCESS";
            } else {
                return "DB_ADD_FAILED";
            }
        }
    }

    // 退选课程
    public boolean dropCourse(int studentId, int courseId) {
        List<CourseSelection> selections = courseSelectionDAO.getCourseSelectionsByStudentId(studentId);
        for (CourseSelection selection : selections) {
            if (selection.getStudentId() == studentId && 
                    selection.getCourseId() == courseId && 
                    "已选".equals(selection.getStatus())) {
                selection.setStatus("已退选");
                System.out.println("Attempting to drop course. Selection ID: " + selection.getId() + ", Status: " + selection.getStatus());
                return courseSelectionDAO.updateCourseSelection(selection);
            }
        }
        return false;
    }

    // 录入成绩
    public boolean inputScore(int studentId, int courseId, double score) {
        List<CourseSelection> selections = courseSelectionDAO.getCourseSelectionsByStudentId(studentId);
        for (CourseSelection selection : selections) {
            if (selection.getStudentId() == studentId && 
                    selection.getCourseId() == courseId && 
                    "已选".equals(selection.getStatus())) {
                selection.setScore(score);
                return courseSelectionDAO.updateCourseSelection(selection);
            }
        }
        return false;
    }

    // 获取学生的选课列表
    public List<CourseSelection> getStudentCourses(int studentId) {
        return courseSelectionDAO.getCourseSelectionsByStudentId(studentId);
    }

    // 获取课程的学生列表
    public List<CourseSelection> getCourseStudents(int courseId) {
        return courseSelectionDAO.getCourseSelectionsByCourseId(courseId);
    }

    // 删除与指定课程ID相关的所有选课记录
    public boolean deleteSelectionsByCourseId(int courseId) {
        return courseSelectionDAO.deleteSelectionsByCourseId(courseId);
    }

    // 获取学生成绩
    public double getStudentScore(int studentId, int courseId) {
        List<CourseSelection> selections = courseSelectionDAO.getCourseSelectionsByStudentId(studentId);
        return selections.stream()
                .filter(s -> s.getStudentId() == studentId && s.getCourseId() == courseId)
                .mapToDouble(CourseSelection::getScore)
                .findFirst()
                .orElse(0.0);
    }
} 